<template>
    <div>
        <el-dialog :title="$t('basItemRoute.import')" v-model="visible" height="2000" width="1500"
            :close-on-click-modal="false" draggable>

            <!--查询表单-->
            <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">

                <el-form-item :label="$t('basItemRoute.excelFile')" prop="excelFile">
                    <el-input v-model="state.queryForm.excelFile" style="width: 500px" clearable disabled
                        :placeholder="$t('basItemRoute.selectExcelFile')">
                        <template #append>
                            <el-upload ref="uploadRef" class="upload-demo" :headers="headers"
                                action='/api/wms/User/CheckImportUser' name="excelFile" :show-file-list="false"
                                :on-success="handleSuccess" :on-error="handleError">
                                <template #trigger>
                                    <el-button type="primary">{{ $t('basItemRoute.select')
                                        }}<el-icon><Select /></el-icon></el-button>
                                </template>
                            </el-upload>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button icon="download" type="info" @click="exportTemplate">
                        {{ $t('basItemRoute.downloadTemplate') }}
                    </el-button>
                </el-form-item>
            </el-form>
            <!--查询结果的列表-->
            <el-table :data="state.dataList" highlight-current-row v-loading="state.loading" border
                :cell-style="tableStyle.cellStyle" stripe :header-cell-style="tableStyle.headerCellStyle">
                <el-table-column type="selection" width="40" align="center" />
                <el-table-column type="index" label="#" width="80" />
                <el-table-column prop="errorMsg" :label="$t('bar.errorMsg')" show-overflow-tooltip>
                    <template #default="scope">
                        <!--根据不同的状态选择不同的颜色的tag-->
                        <el-tag size="large" type="danger" v-if="scope.row.errorMsg !== null">
                            {{ scope.row.errorMsg }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="workNumber" :label="$t('message.userNo')" />
                <el-table-column prop="name" :label="$t('message.userName')" />
                <el-table-column prop="department" :label="$t('productlineUser.deptartment')" />
                <el-table-column prop="sex" :label="$t('productlineUser.sex')" />
                <el-table-column prop="tel" :label="$t('productlineUser.tel')" />
                <el-table-column prop="isOutStr" :label="$t('productlineUser.isOut')" />
            </el-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
                    <el-button type="primary" @click="onSubmit"
                        :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { BasicTableProps, useTable } from "/@/hooks/table";
import { useMessage, useMessageBox } from "/@/hooks/message";
import ExcelJS from 'exceljs';
import { ImportUser } from '/@/api/platform/mes/productlineUser';
import { Session } from '/@/utils/storage';

const { t } = useI18n();

// 定义变量内容
const loading = ref(false);
const visible = ref(false);
const emits = defineEmits(['getChildren'])
const dataForm = reactive({
    excelFile: '',
})
/**
 * 计算请求头部信息
 */
const headers = computed(() => {
    return {
        Authorization: 'Bearer ' + Session.getToken(),
        'TENANT-ID': Session.getTenant(),
    };
});

//上传成功事件
const handleSuccess = (data: any, uploadFile: any) => {
    if (data.msg != "null") {
        useMessage().error(data.msg);
    } else {
        state.queryForm.excelFile = uploadFile.name
        state.dataList = data.data
    }
}
const handleError = (error: any) => { }

//导出模板
const exportTemplate = () => {
    // 创建工作簿对象
    const workbook = new ExcelJS.Workbook();

    // 创建工作表对象
    const worksheet = workbook.addWorksheet('Sheet1');

    // 添加表头行
    worksheet.addRow(['员工工号', '员工名称', '部门', '性别', '电话', '是否外派']);

    // 保存Excel文件
    workbook.xlsx.writeBuffer().then(buffer => {
        // 创建Blob对象
        const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

        // 创建下载链接
        const url = URL.createObjectURL(blob);

        // 创建下载元素并触发下载
        const link = document.createElement('a');
        link.href = url;
        link.download = '人员导入模板.xlsx';
        link.click();

        // 释放URL对象
        URL.revokeObjectURL(url);
    });
}

//查询
const state: BasicTableProps = reactive<BasicTableProps>({
    queryForm: {},
    pageList: ""
})


// 提交
const onSubmit = async () => {
    if (state.dataList?.length === 0) {
        useMessage().error(t('bar.importDataIsNull'));
        return false;
    }

    //如果导入的Excel存在默认版本就弹提示框
    var iserror = false;

    state.dataList?.forEach((element: { errorMsg: any; }) => {
        if (element.errorMsg !== null && element.errorMsg.length > 0) {
            iserror = true
        }
    })

    if (!iserror) {
        await callInterface();
    }
};

const callInterface = async () => {
    try {
        loading.value = true;
        await ImportUser(state.dataList).then((res) => {
            console.log(res);
        });
        useMessage().success(t('bar.importSuccess'));
        visible.value = false;
        emits('getChildren', loading);
    } catch (err: any) {
        useMessage().error(err.msg);
    } finally {
        loading.value = false;
    }
}

// 打开弹框
const openAddDialog = () => {
    visible.value = true;
    // 重置表单数据
    nextTick(() => {
        state.queryForm.excelFile = null;
        state.dataList = [];
    });

};

const {
    getDataList,
    currentChangeHandle,
    sizeChangeHandle,
    sortChangeHandle,
    downBlobFile,
    tableStyle
} = useTable(state)

// 暴露变量
defineExpose({
    openAddDialog
});
</script>